package ruanjian.dao.Impl;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import ruanjian.dao.UserDao;
import ruanjian.domain.User;
import ruanjian.util.JDBCUtils;

import java.util.List;

public class UserDaoImpl implements UserDao {
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<User> findList() {
        String sql = "select * from user ";
        return template.query(sql,new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public int update(User user) {
        String sql = "update user set name = ?,gender = ?,age = ?,address = ?,qq = ?,email = ? where id = ?";
        return template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId());
    }

    @Override
    public int add(User user) {
        String sql = "insert into user value (?,?,?,?,?,?,?,?,?)";
        return template.update(sql,null,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),null,null);
    }

    @Override
    public User login(User user) {
        try {
            String sql = "select * from user where username = ? and password = ?";
            return template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),user.getUsername(),user.getPassword());
        }catch (Exception e){
            return null;
        }

    }

    @Override
    public User findById(Integer id) {
        String sql = "select * from user where id = ?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),id);
    }

    @Override
    public int delete(Integer id) {
        String sql = "delete from user where id = ?";
        return template.update(sql,id);
    }
}
